<template>
  <div>
    <el-container class='subWidth'>
      <el-header class='subheader'
                 style="height: 48px; background-color: white; margin: 2px; padding: 2px; border-radius: 5px">
        <el-form :inline="true" class="demo-form-inline" label-position="left" label-width="80px">
          <el-form-item label="商品名称">
            <el-input v-model="searchQuery.name" @keyup.enter="fetchItems"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="fetchItems">查询</el-button>
            <el-button type="primary" @click="resetSearch">重置</el-button>
            <el-button type="primary" @click="showAddDialog">新增</el-button>
          </el-form-item>
        </el-form>
      </el-header>
      <el-main id='tableContent'>
        <el-table :data="items" show-header="true" style="width: 100%">
          <!--          <el-table-column align="center" type="selection" width="42"></el-table-column>-->
          <el-table-column align="center" label="编号" prop="id" width="45"></el-table-column>
          <el-table-column align="center" label="商品名称" prop="name" width="150"></el-table-column>
          <el-table-column align="center" label="单价" prop="price"></el-table-column>
          <el-table-column align="center" label="库存" prop="stock"></el-table-column>
<!--          <el-table-column align="center" label="图片">
            <template slot-scope="scope">
              <img :src="scope.row.imgUrl" style="width: 50px; height: 50px; object-fit: cover;"/>
            </template>
          </el-table-column>-->
          <el-table-column align="left" label="描述" prop="describe" width="150"></el-table-column>
          <el-table-column align="center" label="尺寸" prop="size"></el-table-column>
          <el-table-column align="center" label="状态">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.isDelete === 0" type="success">已上架</el-tag>
              <el-tag v-else type="danger">未上架</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="推荐">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.isRecommed === 0" type="info">未推荐</el-tag>
              <el-tag v-else type="">推荐</el-tag>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="200">
            <template slot-scope="scope">
              <el-button type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-button plain type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

      </el-main>
      <!-- 新增/编辑商品对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" height="400px" width="450px">
        <div class="el-dialog-div" >
          <el-form :model="currentItem" label-width="100px">
<!--            <el-form-item label="图片">
              <el-upload
                  :on-success="handleAvatarSuccess"
                  :show-file-list="false"
                  action="https://localhost:8082/files/upload"
                  class="avatar-uploader"
              >
                <img v-if="currentItem.imgUrl" :src="currentItem.imgUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>-->
            <el-form-item label="商品名称">
              <el-input v-model="currentItem.name"></el-input>
            </el-form-item>
            <el-form-item label="单价">
              <el-input v-model="currentItem.price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="库存">
              <el-input v-model="currentItem.stock" type="number"></el-input>
            </el-form-item>
            <el-form-item label="描述">
              <el-input v-model="currentItem.describe" type="textarea"></el-input>
            </el-form-item>
            <el-form-item label="尺寸">
              <el-select v-model="currentItem.selectedSizes" multiple>
                <el-option v-for="size in sizes" :key="size" :label="size" :value="size"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否上架">
              <el-switch v-model="currentItem.isDelete"></el-switch>
            </el-form-item>
            <el-form-item label="是否推荐">
              <el-switch v-model="currentItem.isRecommed"></el-switch>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveForm">保存</el-button>
         </span>
      </el-dialog>

      <!--      <div style="margin-top: 20px">-->
      <!--        <el-button @click="toggleSelection([tableData[1], tableData[2]])">切换第二、第三行的选中状态</el-button>-->
      <!--        <el-button @click="toggleSelection()">取消选择</el-button>-->
      <!--      </div>-->
      <!--分页-->
      <MyPagination :total="total"/>
    </el-container>

  </div>
</template>
<script>
import axios from "axios";
import MyPagination from "@/components/MyPagination.vue";
import '@/assets/add.css'

export default {
  components: {
    MyPagination
  },
  data() {
    return {
      searchQuery: {
        name: ''
      },
      selectedSizes: [],// 新增用于存储选中尺寸的数组
      items: [],
      sizes: ['XS', 'S', 'M', 'L', 'XL', 'XXL'],
      dialogVisible: false,
      dialogTitle: '新增商品',
      currentItem: {
        id: null,
        name: null,
        price: null,
        stock: null,
        imgUrl: null,
        describe: null,
        size: null,
        isDelete: null,
        isRecommed: null
      },
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示的条目数
      total: 0, // 总条目数
    };
  },
  methods: {
    handleAvatarSuccess(res) {
      this.currentItem.imgUrl = res.data;
    },
    // 在 methods 中定义的 add 方法，用于打开对话框并设置标题
    add(id) {
      this.dialogVisible = true;
      this.resetForm();
      if (id) {
        this.dialogTitle = '编辑商品';
        // 假设 findItemById 是一个方法，用于根据 ID 查询商品详情
        this.findItemById(id);
      } else {
        this.dialogTitle = '新增商品';
      }
    },
    // 用于打开新增商品对话框的方法
    showAddDialog() {
      this.dialogVisible = true; // 设置对话框为可见
      this.resetForm(); // 重置表单
      this.dialogTitle = '新增商品'; // 设置对话框标题为“新增商品”
    },
    resetForm() {
      this.currentItem = {
        id: null,
        name: '',
        price: 0,
        stock: 0,
        imgUrl: null,
        describe: '',
        size: '',
        isDelete: false,
        isRecommed: false
      };
    },
    findItemById(id) {
      // 假设有一个方法来根据ID查询商品详情
      axios.get(`/item/find/${id}`).then(response => {
        this.currentItem = response.data;
      }).catch(error => {
        console.error("Error finding item by id:", error);
      });
    },
    saveForm() {
      const itemToSubmit = {
        ...this.currentItem,
        isDelete: this.currentItem.isDelete ? 1 : 0, // 将布尔值转换为整数
        isRecommed: this.currentItem.isRecommed ? 1 : 0 // 将布尔值转换为整数
      };
      itemToSubmit.size = this.currentItem.selectedSizes.join(',');
      if (this.currentItem.id) {
        // 执行修改操作
        axios.put("/item/update", itemToSubmit).then(response => {
          // 使用 response 数据
          console.log('Update response:', response.data);
          this.dialogVisible = false;
          this.fetchItems();
          this.$message.success('商品信息更新成功');
        }).catch(error => {
          console.error("Error updating item:", error);
          this.$message.error('商品信息更新失败');
        });
      } else {
        // 执行新增操作
        axios.post("/item/add", itemToSubmit).then(response => {
          // 使用 response 数据
          console.log('Add response:', response.data);
          this.dialogVisible = false;
          this.fetchItems();
          this.$message.success('商品新增成功');
        }).catch(error => {
          console.error("Error adding item:", error);
          this.$message.error('商品新增失败');
        });
      }
    },
    fetchItems() {
      const params = this.searchQuery.name ? {name: this.searchQuery.name} : {};
      axios.get("/item/find", {params}).then(response => {
        this.items = response.data;
      }).catch(error => {
        console.error("Error fetching items:", error);
      });
    },
    resetSearch() {
      this.searchQuery.name = '';
      this.fetchItems(); // 重置后重新获取所有商品列表
    },

    handleEdit(index, row) {
      this.dialogVisible = true; // 打开对话框
      this.dialogTitle = '编辑商品'; // 设置对话框标题
      // 将当前行的数据复制到 currentItem，用于在对话框中显示
      // 确保将 isDelete 和 isRecommed 转换为布尔值
      this.currentItem = {
        ...row,
        isDelete: row.isDelete === 1, // 将 1 转换为 true，0 转换为 false
        isRecommed: row.isRecommed === 1,// 将 1 转换为 true，0 转换为 false
        selectedSizes: row.size.split(',') // 将尺寸字符串转换为数组
      };
    },

    handleDelete(index, row) {
      axios.delete(`/item/delete/${row.id}`).then(response => {
        // 检查后端返回的响应数据
        if (response.data.success) { // 假设后端返回的数据包含一个 success 字段
          this.items.splice(index, 1);
          this.fetchItems();
          console.log("删除成功")
          this.$message.success('商品删除成功');
        }
      })
    }
  },
  mounted() {
    this.fetchItems(); // 页面加载时获取商品列表
  }

};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 24px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 150px;
  height: 150px;
  display: block;
}
.el-input{
  width: 100%;
}
</style>
